package proyecto.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import proyecto.excepcion.DAOExcepcion;
import proyecto.modelo.Boleta;

public class BoletaDAOImpl  extends HibernateDaoSupport implements BoletaDAO {
	
	protected Log log = LogFactory.getLog(getClass());

	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public Boleta insertar(Boleta modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().save(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	

	@SuppressWarnings("unchecked")
	public List<Boleta> listar() throws DAOExcepcion {
		log.info("listar()");
		List<Boleta> lista = new ArrayList<Boleta>();
		try {
			lista = getHibernateTemplate().find("from Boleta");
		} catch (DataAccessException e) {
			log.error(e.toString());
			throw new DAOExcepcion(e.getMessage());
		}
		return lista;
	}

	public Boleta obtener(int coBoleta) throws DAOExcepcion {
		log.info("obtener() : " + coBoleta);
		Boleta modelo = new Boleta();
		try {
			modelo = (Boleta) getHibernateTemplate().find(
					"from Boleta a where trim(a.coBoleta) = ?",
					coBoleta + "").get(0);
		} catch (Exception e) {
			log.error("Error: " + e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	
	public Boleta actualizar(Boleta modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().update(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	
	public void eliminar(int coBoleta) throws DAOExcepcion {
		Boleta modelo = new Boleta();
		modelo.setCoBoleta(coBoleta);
		try {
			getHibernateTemplate().delete(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
	}
}
